<?php

class MemberController {
	private $m_loginHandler;
	private $m_loginView;
	private $m_memberHandler;
	private $m_memberView;
	private $m_memberDAL;

	public function __construct($a_loginHandler, $a_loginView, $a_memberHandler, $a_memberView, $a_memberDAL) {
		$this->m_loginHandler = $a_loginHandler;
		$this->m_loginView = $a_loginView;
		$this->m_memberHandler = $a_memberHandler;
		$this->m_memberView  =$a_memberView;
		$this->m_memberDAL = $a_memberDAL;
	}

	public function DoControl() {
		$member = new Member(); 
		$userExists = false;
		$ssnExists = false;
		$errors = false;
			
		// If someone's tried to become member we should..
		if ($this->m_memberView -> TriedToBecomeMember()) {
			
			//make them a premember object, 
			$newMember = $this->m_memberHandler->getNewMember($this -> m_memberView -> GetFirstName(), 
			$this -> m_memberView -> GetLastName(), 
			$this -> m_memberView -> GetUserName(), 
			$this -> m_memberView -> GetPassword(),
		  	$this -> m_memberView -> GetCheckPassword(), 
			$this -> m_memberView -> GetMail(), 
			$this -> m_memberView -> GetSsn());
			
			//check if the member name and 
			if($this->m_memberDAL->UserNameExists($this->m_memberView->GetUserName())){
				$userExists = true;
				$errors = true;
			}
			//ssn already exists
			if($this->m_memberDAL->SsnExists($this->m_memberView->GetSsn())){
				$ssnExists = true;
				$errors = true;
			}
			
			// Let's validate everything, shall we. 
			if ($this -> m_memberView ->HasError() == true || $errors) {
				//The validation didn't go so well, give the user another shot with a new refilled form. 				
				return $this->m_memberView->ReFillDoBecomeMemberForm($userExists, $ssnExists);
			}else{
				//Wohoo, the user made it past validation. Let's make them a member and log them in right away!
				$this->m_memberDAL -> AddMember($newMember);
				$this->m_loginHandler->DoLogin($newMember->userName, $newMember->password);
				echo"Membercontroller:DoControl";
				header("Location: index.php");		
			}
		}else{
			//Well, make a becomememberform so that everyone can be members... hopefully not everyone.  
			return $this->m_memberView->DoBecomeMemberForm();
		} 		
	}
}
